package com.mms.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JdbcUtils {
	// 把各个连接参数表示成静态常量，便于在其它地方引用
	public static final String DRIVER_CLASS_NAME = "com.mysql.cj.jdbc.Driver";
	public static final String URL = "jdbc:mysql://localhost:3306/grtsmms";
	public static final String USER = "root";
	public static final String PASSWORD = "root";
	// 静态代码段，在JVM加载JdbcUtils这个类的时候执行一次，之后再也不执行了
	static {
		try {
			Class.forName(DRIVER_CLASS_NAME);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 创建数据库连接对象
	 * @return
	 * @throws SQLException
	 */
	public static Connection getConnection() throws SQLException {
		return DriverManager.getConnection(URL, USER, PASSWORD);
	}
	
	public static void close(ResultSet rs) {
		close(rs, null, null);
	}
	
	public static void close(Statement stmt) {
		close(null, stmt, null);
	}
	
	public static void close(Connection conn) {
		close(null, null, conn);
	}
	
	public static void close(Statement stmt, Connection conn) {
		close(null, stmt, conn);
	}

	public static void close(ResultSet rs, Statement stmt, Connection conn) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (stmt != null) {
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
}
